package com.tutu.cmn.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tutu.cmn.service.DictService;
import com.tutu.common.result.Result;
import com.tutu.model.cmn.Dict;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.cache.annotation.Cacheable;

import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Program: yygh_parent
 * @Description: 数据字段控制层
 * @Author: JK.TuTu
 * @Create: 2022-09-18 18:03
 **/
@Slf4j
@RestController
@RequestMapping("/admin/cmn/dict")
@CrossOrigin
public class DictController {

    @Autowired
    private DictService dictService;

    /**
     * 根据父节点id获取子节点数据列表
     *
     * @param parentId
     * @return
     */
    @ApiOperation("根据父节点id获取子节点数据列表")
    @GetMapping("findChildrenById/{parentId}")
    @Cacheable(value = "dict",key = "'parentId_'+#parentId")
    public Result findChildrenById(@PathVariable("parentId") Long parentId) {
        LambdaQueryWrapper<Dict> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Dict::getParentId, parentId);
        List<Dict> distList = dictService.list(queryWrapper).stream().map((item) -> {
            boolean flag = this.checkChildren(item.getParentId());
            //向查询到的每条数据插入是否有子节点
            item.setHasChildren(flag);
            return item;
        }).collect(Collectors.toList());
        return Result.ok(distList);
    }

    /**
     * excel文件导出&&模板下载
     * @param response
     * @param flag   1:文件导出  0:模板下载
     */
    @ApiOperation(value = "excel文件导出")
    @GetMapping(value = "/exportData")
    public void exportData(HttpServletResponse response,@RequestParam int flag) {
        dictService.exportData(response, flag);
    }


    /**
     * excel文件导入
     * @param file
     * @return
     */
    @ApiOperation(value = "excel文件导入")
    @PostMapping("importData")
    public Result importData(MultipartFile file) {
        dictService.importDictData(file);
        return Result.ok();
    }

    /**
     * 根据父节点id查询有无子节点
     *
     * @param parentId
     * @return
     */
    private boolean checkChildren(Long parentId) {
        LambdaQueryWrapper<Dict> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Dict::getParentId, parentId);
        List<Dict> list = dictService.list(queryWrapper);
        return list.size() > 0;
    }
}
